<?php
class Reg extends CI_Controller
{
	// Used for registering and changing password form validation
	private $min_username;
	private $max_username;
	private $min_password;
	private $max_password;

	function __construct()
	{
		parent::__construct();
		$this->min_username = MIN_USERNAME;
		$this->max_username = MAX_USERNAME;
		$this->min_password = MIN_PASSWORD;
		$this->max_password = MAX_PASSWORD;
//		$this->output->enable_profiler(TRUE);

		$this->load->library('form_validation');
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('City_m','city');
	}

	function index()
	{
		$this->login();
	}

	function reg2(){
		$val = $this->form_validation;

		$val->set_rules('email', '邮箱地址', 'trim|required|xss_clean|valid_email|callback_email_check');	
		$val->set_rules('city', '城市', 'trim|required|integer');	
		
		if (!$val->run()){
			$this->session->set_flashdata('err', validation_errors());
			$this->session->set_flashdata('femail', $val->set_value('email'));
			$this->session->set_flashdata('fcity', $val->set_value('city'));
			redirect('');
		}else{
			$this->load->model('Category_m','category');
			$all_cat = $this->category->get_all_category();
			
			$data = array(
					'email' => $val->set_value('email'),
					'city' => $val->set_value('city'),
					'all_cat' => $all_cat
					);
			$this->load->view('user/reg2',$data);
		}
	}
	
	function reg3(){
		$val = $this->form_validation;

		$val->set_rules('email', '邮箱地址', 'trim|required|xss_clean|valid_email|callback_email_check');	
		$val->set_rules('city', '城市', 'trim|required|integer');	
		
		if (!$val->run()){
			$this->session->set_flashdata('err', validation_errors());
			$this->session->set_flashdata('femail', $val->set_value('email'));
			$this->session->set_flashdata('fcity', $val->set_value('city'));
			redirect('');
		}else{
			$this->load->model('Site_m','site');
			$all_site = $this->site->get_all_site();
			
			$data = array(
					'email' => $val->set_value('email'),
					'city' => $val->set_value('city'),
					'all_site' => $all_site,
					'tag' => $this->input->post('tag')
					);
			$this->load->view('user/reg3',$data);
		}
	}
	
	/* Callback function */
	function username_check($username)
	{
		$result = $this->dx_auth->is_username_available($username);
		if ( ! $result)
		{
			$this->form_validation->set_message('username_check', 'Username already exist. Please choose another username.');
		}

		return $result;
	}

	function email_check($email)
	{
		$result = $this->dx_auth->is_email_available($email);
		if ( ! $result)
		{
			$this->form_validation->set_message('email_check', '电子邮箱地址已存在');
		}

		return $result;
	}

	function captcha_check($code)
	{
		$result = TRUE;

		if ($this->dx_auth->is_captcha_expired())
		{
			// Will replace this error msg with $lang
			$this->form_validation->set_message('captcha_check', '验证码已过期，请重试');
			$result = FALSE;
		}
		elseif ( ! $this->dx_auth->is_captcha_match($code))
		{
			$this->form_validation->set_message('captcha_check', '验证码不匹配');
			$result = FALSE;
		}

		return $result;
	}

	function recaptcha_check()
	{
		$result = $this->dx_auth->is_recaptcha_match();
		if ( ! $result)
		{
			$this->form_validation->set_message('recaptcha_check', 'Your confirmation code does not match the one in the image. Try again.');
		}

		return $result;
	}

	/* End of Callback function */


	function login()
	{
		$ret = false;
		if ( ! $this->dx_auth->is_logged_in())
		{
			$val = $this->form_validation;

			// Set form validation rules
			$val->set_rules('username', 'Username', 'trim|required|xss_clean');
			$val->set_rules('password', 'Password', 'trim|required|xss_clean');
//			$val->set_rules('remember', 'Remember me', 'integer');

			// Set captcha rules if login attempts exceed max attempts in config
			if ($this->dx_auth->is_max_login_attempts_exceeded())
			{
				$val->set_rules('captcha', 'Confirmation Code', 'trim|required|xss_clean|callback_captcha_check');
			}

//			if ($val->run() AND $this->dx_auth->login($val->set_value('username'), $val->set_value('password'), $val->set_value('remember')))
			if ($val->run() AND $this->dx_auth->login($val->set_value('username'), $val->set_value('password'), 1))
			{
				// Redirect to homepage
//				redirect('', 'location');
				$ret = true;
			}
			else
			{
				// Check if the user is failed logged in because user is banned user or not
//				if ($this->dx_auth->is_banned())
//				{
//					// Redirect to banned uri
//					$this->dx_auth->deny_access('banned');
//				}
//				else
//				{
//					// Default is we don't show captcha until max login attempts eceeded
//					$data['show_captcha'] = FALSE;
//
//					// Show captcha if login attempts exceed max attempts in config
//					if ($this->dx_auth->is_max_login_attempts_exceeded())
//					{
//						// Create catpcha
//						$this->dx_auth->captcha();
//
//						// Set view data to show captcha on view file
//						$data['show_captcha'] = TRUE;
//					}
//
//					// Load login page view
//					$this->load->view($this->dx_auth->login_view, $data);
//				}
			}
		}
		else
		{
			$data['auth_message'] = '您已经是登录状态';
//			$this->load->view($this->dx_auth->logged_in_view, $data);
		}
		
		echo json_encode(array('ret' => $ret));
	}

	function logout()
	{
		$this->dx_auth->logout();

//		$data['auth_message'] = 'You have been logged out.';
//		$this->load->view($this->dx_auth->logout_view, $data);
		redirect('', 'location');
	}

	function register()
	{
		if ( ! $this->dx_auth->is_logged_in() AND $this->dx_auth->allow_registration)
		{
			$val = $this->form_validation;

			// Set form validation rules
//			$val->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->min_username.']|max_length['.$this->max_username.']|callback_username_check|alpha_dash');
			$val->set_rules('password', '密码', 'trim|required|xss_clean|min_length['.$this->min_password.']|max_length['.$this->max_password.']|matches[confirm_password]');
			$val->set_rules('confirm_password', '验证密码', 'trim|required|xss_clean');
			$val->set_rules('email', '邮箱地址', 'trim|required|xss_clean|valid_email|callback_email_check');	
			$val->set_rules('city', '城市', 'trim|required|integer');

			if ($this->dx_auth->captcha_registration)
			{
				$val->set_rules('captcha', '验证码', 'trim|xss_clean|required|callback_captcha_check');
			}

			$tag = $this->input->post('tag');
			$site = $this->input->post('site');
			$data = array(
					'email' => $this->input->post('email'),
					'city' => $this->input->post('city'),
					'tag' => $tag,
					'site' => $site,
					'reg3' => $this->input->post('reg3')
					);

			// Run form validation and register user if it's pass the validation
			if ($val->run() AND $this->dx_auth->register($val->set_value('email'), $val->set_value('password'), $val->set_value('email')))
			{
				$this->dx_auth->login($val->set_value('email'), $val->set_value('password'));
				
				// Set success message accordingly
				if ($this->dx_auth->email_activation)
				{
					$data['auth_message'] = 'You have successfully registered. Check your email address to activate your account.';
				}
				else
				{
					$data['auth_message'] = 'You have successfully registered. '.anchor(site_url($this->dx_auth->login_uri), 'Login');
				}
				
				$user_id = $this->dx_auth->get_user_id();
				
				$this->load->model('dx_auth/user_profile', 'user_profile');
				$city_id = intval($data['city']);
				if($city_id > 0){
					$this->user_profile->set_profile($user_id,array('city_id' => $city_id));
					$this->load->model('city_m', 'city');
					$city = $this->city->get_city_by_id($city_id);
					if($city){
						$this->city->set_city_info_in_session($city_id,$city);
					}
				}

				if($tag && is_array($tag)){
					$this->load->model('Category_m','category');
					$this->category->set_user_category($user_id,$tag);
				}
				
				if($site && is_array($site)){
					$this->load->model('Site_m','site');
					$this->site->set_user_sites($user_id,$site);
				}
				
				redirect('', 'location');
			}
			else
			{
				// Is registration using captcha
				if ($this->dx_auth->captcha_registration)
				{
					$this->dx_auth->captcha();
				}

				// Load registration page
				$this->load->view('user/reg4',$data);
			}
		}
		elseif ( ! $this->dx_auth->allow_registration)
		{
			$data['auth_message'] = 'Registration has been disabled.';
			$this->load->view($this->dx_auth->register_disabled_view, $data);
		}
		else
		{
			$data['auth_message'] = 'You have to logout first, before registering.';
			$this->load->view($this->dx_auth->logged_in_view, $data);
		}
	}

	function register_recaptcha()
	{
		if ( ! $this->dx_auth->is_logged_in() AND $this->dx_auth->allow_registration)
		{
			$val = $this->form_validation;

			// Set form validation rules
			$val->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->min_username.']|max_length['.$this->max_username.']|callback_username_check|alpha_dash');
			$val->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->min_password.']|max_length['.$this->max_password.']|matches[confirm_password]');
			$val->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean');
			$val->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|callback_email_check');

			// Is registration using captcha
			if ($this->dx_auth->captcha_registration)
			{
				// Set recaptcha rules.
				// IMPORTANT: Do not change 'recaptcha_response_field' because it's used by reCAPTCHA API,
				// This is because the limitation of reCAPTCHA, not DX Auth library
				$val->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback_recaptcha_check');
			}

			// Run form validation and register user if it's pass the validation
			if ($val->run() AND $this->dx_auth->register($val->set_value('username'), $val->set_value('password'), $val->set_value('email')))
			{
				// Set success message accordingly
				if ($this->dx_auth->email_activation)
				{
					$data['auth_message'] = 'You have successfully registered. Check your email address to activate your account.';
				}
				else
				{
					$data['auth_message'] = 'You have successfully registered. '.anchor(site_url($this->dx_auth->login_uri), 'Login');
				}

				// Load registration success page
				$this->load->view($this->dx_auth->register_success_view, $data);
			}
			else
			{
				// Load registration page
				$this->load->view('auth/register_recaptcha_form');
			}
		}
		elseif ( ! $this->dx_auth->allow_registration)
		{
			$data['auth_message'] = 'Registration has been disabled.';
			$this->load->view($this->dx_auth->register_disabled_view, $data);
		}
		else
		{
			$data['auth_message'] = 'You have to logout first, before registering.';
			$this->load->view($this->dx_auth->logged_in_view, $data);
		}
	}

	function activate()
	{
		// Get username and key
		$username = $this->uri->segment(3);
		$key = $this->uri->segment(4);

		// Activate user
		if ($this->dx_auth->activate($username, $key))
		{
			$data['auth_message'] = 'Your account have been successfully activated. '.anchor(site_url($this->dx_auth->login_uri), 'Login');
			$this->load->view($this->dx_auth->activate_success_view, $data);
		}
		else
		{
			$data['auth_message'] = 'The activation code you entered was incorrect. Please check your email again.';
			$this->load->view($this->dx_auth->activate_failed_view, $data);
		}
	}

	function forgot_password()
	{
		$val = $this->form_validation;

		// Set form validation rules
		$val->set_rules('login', '电子邮箱', 'trim|required|xss_clean');

		$data = array();
		// Validate rules and call forgot password function
		if ($val->run() AND $this->dx_auth->forgot_password($val->set_value('login')))
		{
//			$data['auth_message'] = 'An email has been sent to your email with instructions with how to activate your new password.';
//			$this->load->view($this->dx_auth->forgot_password_success_view, $data);
			$data = array(
						'ret' => true,
						'msg' => '已向您发送了密码激活邮件，请检查您的邮箱'
						);
		}
		else
		{
			$data = array(
						'ret' => false,
						'msg' => $this->dx_auth->get_auth_error()
						);
//			$this->load->view($this->dx_auth->forgot_password_view);
		}
		echo json_encode($data);
	}

	function reset_password()
	{
		// Get username and key
		$username = $this->uri->segment(3);
		$key = $this->uri->segment(4);

		$data = array();
		// Reset password
		if ($this->dx_auth->reset_password($username, $key))
		{
			$data['title'] = '密码更改';
			$data['body'] = '您的密码已更改成功，请通过邮件中的新密码进行登录，并可在登录后更改密码';
			$data['addition'] = anchor(site_url(''), '首页');
//			$data['auth_message'] = 'You have successfully reset you password, '.anchor(site_url($this->dx_auth->login_uri), 'Login');
//			$this->load->view($this->dx_auth->reset_password_success_view, $data);
		}
		else
		{
			$data['title'] = '密码更改';
			$data['body'] = '抱歉您的密码更改失败，请仔细阅读您的邮件';
			$data['addition'] = anchor(site_url(''), '首页');
//			$data['auth_message'] = 'Reset failed. Your username and key are incorrect. Please check your email again and follow the instructions.';
//			$this->load->view($this->dx_auth->reset_password_failed_view, $data);
		}
		$this->load->view('notice',$data);
	}

	function change_password()
	{
		// Check if user logged in or not
		if ($this->dx_auth->is_logged_in())
		{
			$val = $this->form_validation;

			// Set form validation
			$val->set_rules('old_password', 'Old Password', 'trim|required|xss_clean|min_length['.$this->min_password.']|max_length['.$this->max_password.']');
			$val->set_rules('new_password', 'New Password', 'trim|required|xss_clean|min_length['.$this->min_password.']|max_length['.$this->max_password.']|matches[confirm_new_password]');
			$val->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|xss_clean');

			// Validate rules and change password
			if ($val->run() AND $this->dx_auth->change_password($val->set_value('old_password'), $val->set_value('new_password')))
			{
				$data['auth_message'] = 'Your password has successfully been changed.';
				$this->load->view($this->dx_auth->change_password_success_view, $data);
			}
			else
			{
				$this->load->view($this->dx_auth->change_password_view);
			}
		}
		else
		{
			// Redirect to login page
			$this->dx_auth->deny_access('login');
		}
	}
	
	function genCaptcha(){
		$this->dx_auth->captcha();
		$url = $this->dx_auth->get_captcha_image();
		$ret['url'] = $url;
		echo json_encode($ret);
	}

//	function cancel_account()
//	{
//		// Check if user logged in or not
//		if ($this->dx_auth->is_logged_in())
//		{
//			$val = $this->form_validation;
//
//			// Set form validation rules
//			$val->set_rules('password', 'Password', "trim|required|xss_clean");
//
//			// Validate rules and change password
//			if ($val->run() AND $this->dx_auth->cancel_account($val->set_value('password')))
//			{
//				// Redirect to homepage
//				redirect('', 'location');
//			}
//			else
//			{
//				$this->load->view($this->dx_auth->cancel_account_view);
//			}
//		}
//		else
//		{
//			// Redirect to login page
//			$this->dx_auth->deny_access('login');
//		}
//	}
//
//	// Example how to get permissions you set permission in /backend/custom_permissions/
//	function custom_permissions()
//	{
//		if ($this->dx_auth->is_logged_in())
//		{
//			echo 'My role: '.$this->dx_auth->get_role_name().'<br/>';
//			echo 'My permission: <br/>';
//
//			if ($this->dx_auth->get_permission_value('edit') != NULL AND $this->dx_auth->get_permission_value('edit'))
//			{
//				echo 'Edit is allowed';
//			}
//			else
//			{
//				echo 'Edit is not allowed';
//			}
//
//			echo '<br/>';
//
//			if ($this->dx_auth->get_permission_value('delete') != NULL AND $this->dx_auth->get_permission_value('delete'))
//			{
//				echo 'Delete is allowed';
//			}
//			else
//			{
//				echo 'Delete is not allowed';
//			}
//		}
//	}
}
?>